package services

import (
	"accounting-software/dao"
	"accounting-software/models"
	"accounting-software/utils"
	"errors"

	"gorm.io/gorm"
)

// 定义UserService结构体，返回UserDao
type UserService struct {
	userDao *dao.UserDao
}

// 定义实例化UserService的方法
func NewUserService(userDao *dao.UserDao) *UserService {
	return &UserService{userDao: userDao}
}

// 定义添加用户的方法
func (us *UserService) AddUser(username, password string) (*models.User, error) {
	// 加密密码
	hashedPassword, err := utils.HashPassword(password)
	if err != nil {
		return nil, err
	}
	user := &models.User{Name: username, Password: hashedPassword}
	Err := us.userDao.AddUser(user)
	return user, Err

}

// 判断用户名是否可用
func (us *UserService) IsUsernameAvailable(username string) (bool, error) {
	existingUser, err := us.userDao.FindUserByName(username)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return false, err // 数据库查询出错
	}
	return existingUser == nil, nil // 用户不存在则返回 true
}

// 用户登录
func (us *UserService) Login(name, password string) (string, error) {
	user, err := us.userDao.FindUserByName(name)
	if err != nil {
		return "", errors.New("用户不存在")
	}

	// 验证密码
	if !utils.CheckPassword(user.Password, password) {
		// if user.Password != password {
		return "", errors.New("密码错误")
	}
	// 生成JWT Token
	token, err := utils.GenerateJWT(uint(user.ID), user.Name)
	if err != nil {
		return "", errors.New("生成Token失败")
	}

	return token, nil
}
